<?php
// +----------------------------------------------------------------------
// | Author: July
// +----------------------------------------------------------------------
// | 创建时间: 2023-12-27 20:39:42
// +----------------------------------------------------------------------
// | 导入相关操作
// +----------------------------------------------------------------------

namespace july\julyadmin\common\logic;

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;

class ImportLogic
{
    protected $url = '';
    /**
     * 初始化
     * @Author   july
     * @DateTime 2023-09-03
     * @param    string     $url    要导入的文件地址，如./public/uploads/xxx.csv
     */
    public function __construct($url = '')
    {
        $this->url = $url;
    }

    /**
     * 导入excel
     * @Author   july
     * @DateTime 2023-09-03
     * @param    integer     $page     从第几页开始读
     * @param    integer     $rows     读取多少条
     */
    public function import($page = 1, $rows = 500)
    {
        $fileParts = pathinfo($this->url);
        $ext       = strtolower($fileParts['extension']);
        switch ($ext) {
            case "xls":
                $reader = IOFactory::createReader("Xls");
                break;

            case "xlsx":
                $reader = IOFactory::createReader("Xlsx");
                break;

            case "csv":
                $reader = IOFactory::createReader("Csv");
                break;
        }

        $reader->setReadDataOnly(true); //只读
        $spreadsheet = $reader->load($this->url); //载入excel表格 路径和文件名
        $spreadsheet->setActiveSheetIndex(0); //指定excel的sheet 0是第一个
        $worksheet           = $spreadsheet->getActiveSheet();
        $highestRow          = $worksheet->getHighestRow(); // 总行数
        $highestColumn       = $worksheet->getHighestColumn(); //得到最后一列名称，比如F
        $highestColumnLength = Coordinate::columnIndexFromString($highestColumn); //将列名转换为索引，比如1
        $rowData             = [];

        $line = (($page - 1) * $rows);
        if ($line + $rows >= $highestRow) {
            $for_rows = $highestRow - $line;
        } else {
            $for_rows = $rows;
        }
        for ($row = 0; $row < $for_rows; $row++) {
            for ($col = 0; $col < $highestColumnLength; $col++) {
                $rowData[$line + $row + 1][] = $worksheet->getCellByColumnAndRow($col + 1, $line + $row + 1)->getValue();
            }
        }

        $result = [
            'code' => 1,
            'msg'  => '导入成功',
            'data' => [
                'total' => $highestRow,
                'list'  => $rowData,
            ],
        ];
        return $result;
    }
}
